import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Reservation from '../views/Reservation.vue'
import MyReservations from '../views/MyReservations.vue'
import Profile from '../views/Profile.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import Layout from '../components/Layout.vue'
import { userTokenStore } from '../store/userStore'
import { ElMessage } from 'element-plus'


const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/main',
    name: 'Main',
    component: Layout,
    children: [
      {
        path: '',
        redirect: '/main/home'
      },
      {
        path: 'home',
        name: 'Home',
        component: Home,
        meta: { requiresAuth: true }
      },
      {
        path: 'reservation',
        name: 'Reservation',
        component: Reservation,
        meta: { requiresAuth: true }
      },
      {
        path: 'myreservations',
        name: 'MyReservations',
        component: MyReservations,
        meta: { requiresAuth: true }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: Profile,
        meta: { requiresAuth: true }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 添加路由守卫
router.beforeEach((to, from, next) => {
  // 获取 token
  const userStore = userTokenStore();
  const token = userStore.token;
  
  // 如果访问的是登录或注册页面，直接放行
  if (to.path === '/login' || to.path === '/register') {
    next()
    return
  }

  // 如果没有 token 且访问的页面需要认证，重定向到登录页
  if (!token && to.meta.requiresAuth) {
    ElMessage.error('请先登录');
    next('/login')
    return
  }

  // 如果有 token，检查 token 是否过期（这里可以添加 token 验证逻辑）
  if (token) {
    // 这里可以添加 token 验证逻辑，比如调用后端接口验证 token 有效性
    // 如果 token 无效，重定向到登录页
    next()
  }

  next()
})

export default router
